package com.cq.hd.app.controller;

import com.alibaba.fastjson.JSON;
import com.cq.hd.common.constant.RedisKeyConstant;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.entity.UserInfo;
import com.cq.hd.common.utils.JwtUtil;
import com.cq.hd.common.utils.RedisUtil;
import com.cq.hd.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class BaseController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HttpServletRequest request;

    public AppLoginUser getAppLoginUser() {
        try {
            AppLoginUser appLoginUser = new AppLoginUser();
            String token = request.getHeader("Authorization");
            if (StringUtils.isNullOrEmpty(token)) {
                return null;
            }
            String userIdStr = JwtUtil.getAudience(token, 0);
            if (StringUtils.isBlank(userIdStr)) {
                return null;
            }
            Long userId = Long.valueOf(userIdStr);
            appLoginUser.setUserId(userId);
            String userInfoRedis = redisUtil.get(String.format(RedisKeyConstant.USER_INFO_KEY, userIdStr));
            if (StringUtils.isNullOrEmpty(userInfoRedis)) {
                return null;
            }

            UserInfo userInfo = JSON.parseObject(userInfoRedis, UserInfo.class);
            appLoginUser.setUserInfo(userInfo);
            return appLoginUser;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

}
